<%
    Record rg = new Record(task.getSQLCommand().executeQuery("SELECT * FROM grade_master"));
%>
<script language="javascript" runat="server">
    var grade_array = new Array();
<%
	rg.beforeFirst();
	while(rg.next()) {
		String desc = rg.getString("description");
		desc = desc.replace('\n',' ');
		desc = desc.replace('\r',' ');
%>		grade_array[<%=rg.getRow()-1%>] = new Array(<%=rg.getInt("id")%>,<%=rg.getInt("origin_id")%>,<%=rg.getInt("quality_id")%>,"<%=rg.getString("grade_code")%>","<%=rg.getString("name")%>","<%=desc%>");
<%      
    }
    rg.close();
%>	

function findByCode(code)
{
	for (var i = 0; i < grade_array.length; i++) {
		var gr = grade_array[i];
		if (gr[3] == code) return gr;
	}
	return null;
}

function findByGrade(grade)
{
	for (var i = 0; i < grade_array.length; i++) {
		var gr = grade_array[i];
		if (gr[0] == grade) return gr;
	}
	return null;
}

function setGrade(origin,quality,gr_id)
{
	if (gr_id == null) gr_id = "grade_id";
	var list = getObj(gr_id);
	if (list == null) return;
	list.length = 0;
	var op = new Option("",0, true, true);
	list.options[0] = op;
	for (var i = 0; i < grade_array.length; i++) {
		var gr = grade_array[i];
		if (gr[1] == origin && gr[2] == quality) {
			op = new Option(gr[4],gr[0], true, true);
			list.options[list.length] = op;
		}	
	}
}

function codeChanged(obj,gr_id)
{
	if (gr_id == null) gr_id = "grade_id";
	var code = obj.value;
	var gr = findByCode(code);
	if (gr == null) {
		alert("Grade code not found.");
		obj.value = "";
		obj.focus();
		return false;
	}
	setValue("origin_id",gr[1]);
	setValue("quality_id",gr[2]);
	setGrade(gr[1],gr[2],gr_id);
	setValue(gr_id,gr[0]);
	setValue("description",gr[5]);
	return true;
}

function gradeChanged(obj)
{
	var grade = obj.value;
	var gr = findByGrade(grade);
	if (gr == null) {
		if (grade > 0) alert("Grade not found.");
		obj.value = "0";
		obj.focus();
		return false;
	}
	setValue("origin_id",gr[1]);
	setValue("quality_id",gr[2]);
	setValue("grade_code",gr[3]);
	setValue("description",gr[5]);
	return true;
}

function originChanged(obj)
{
	var origin = obj.value;
	var quality = getValue("quality_id");
	setGrade(origin,quality);
	setValue("grade_id",0);
	setValue("grade_code","");
}

function qualityChanged(obj)
{
	var quality = obj.value;
	var origin = getValue("origin_id");
	setGrade(origin,quality);
	setValue("grade_id",0);
	setValue("grade_code","");
}

</script>
